$(function(){
	
	$('#username').on('blur',function(){
		var self = $(this);
		if(self.val().length == 0) {
			self.parent('div').addClass('has-error');
			$('<span class="glyphicon glyphicon-remove form-control-feedback"></span><span class="error">用户名不能为空<span>').insertAfter('#username');
			return;
		}
		$.post('./check.do',{username:$('#username').val()},function(data){
			if(data.exists) {
				self.parent('div').addClass('has-error');
				$('<span class="glyphicon glyphicon-remove form-control-feedback"></span><span class="error">用户名已存在<span>').insertAfter('#username');
			} else {
				self.parent('div').addClass('has-success');
				$('<span class="glyphicon glyphicon-ok form-control-feedback"></span>').insertAfter('#username');
			}
		},'json');
	});
	$('#username').on('focus',function(){
		remove($(this));
	});
	

	$('#password').on('blur',function(){
		var self = $(this);
		if(self.val().length < 6) {
			self.parent('div').addClass('has-error');
			$('<span class="glyphicon glyphicon-remove form-control-feedback"></span><span class="error">用户名不能小于六位<span>').insertAfter('#password');
		} else {
			self.parent('div').addClass('has-success');
			$('<span class="glyphicon glyphicon-ok form-control-feedback"></span>').insertAfter('#password');
		}
		
	});
	$('#password').on('focus',function(){
			remove($(this));
	});
	
	$('#passwordOk').on('blur',function(){
		var self = $(this);
		if(self.val() != $('#password').val()) {
			self.parent('div').addClass('has-error');
			$('<span class="glyphicon glyphicon-remove form-control-feedback"></span><span class="error">两次输入的密码不一致<span>').insertAfter('#passwordOk');
		} else {
			self.parent('div').addClass('has-success');
			$('<span class="glyphicon glyphicon-ok form-control-feedback"></span>').insertAfter('#passwordOk');
		}		
	});
	$('#passwordOk').on('focus',function(){
			remove($(this));
	});
	
	$('#email').on('blur',function(){
		var reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;
		var self = $(this);
		if(!reg.test(self.val())) {
			self.parent('div').addClass('has-error');
			$('<span class="glyphicon glyphicon-remove form-control-feedback"></span><span class="error">邮箱的格式不正确<span>').insertAfter('#email');
		} else {
			self.parent('div').addClass('has-success');
			$('<span class="glyphicon glyphicon-ok form-control-feedback"></span>').insertAfter('#email');
		}		
	});
	$('#email').on('focus',function(){
			remove($(this));
	});
	
});

function remove(th) {
	th.next().remove();
	th.parent('div').removeClass("has-error");
	th.parent('div').removeClass("has-success");
	th.parent('div').children(".error").remove();	
}

function checkInfo() {
	var group = $(".form-group");
	for(var i = 0; i < group.length ; i++) {
		if(!group.eq(i).hasClass("has-success")) {
			break;
		}
	}
	if(i != group.length) {
		alert("对不起,请核对信息后提交");
		return false;
	}
	return true;
}